﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Serilog;
using Serilog.Events;
using Serilog.Filters;
using Volo.Abp;

namespace PHMEE.BackgroundServices
{
    public class Program
    {
        public static async Task<int> Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
#if DEBUG
                .MinimumLevel.Debug()
#else
                .MinimumLevel.Information()
#endif
                .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                .Enrich.FromLogContext()
                .WriteTo.Logger(lc => lc.Filter.ByIncludingOnly(Matching.FromSource("PHMEE.BackgroundServices.CBM"))
                    .WriteTo.Async(c => c.File("Logs/CBM/logs-.txt", rollingInterval: RollingInterval.Day)))
                .WriteTo.Async(c => c.File("Logs/logs-.txt", rollingInterval: RollingInterval.Day))
                .WriteTo.Async(c => c.Console())
                .CreateLogger();

            try
            {
                Log.Information("Starting console host.");
                var builder = CreateHostBuilder(args);

                var host = builder.Build();

                await host.Services.GetRequiredService<IAbpApplicationWithExternalServiceProvider>()
                    .InitializeAsync(host.Services);

                await host.RunAsync();
                return 0;
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly!");
                return 1;
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

        internal static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((context, config) => { })
                .UseAutofac()
                .UseSerilog()
                .ConfigureServices((hostContext, services) =>
                {
                    //services.AddHostedService<MQTTClientHostService>();
                    //services.AddHostedService<PHMEEBackgroundHostedService>();
                    services.AddApplicationAsync<PHMEEBackgroundServicesModule>(options =>
                    {
                        options.Services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog());
                    });
                });
    }
}